// pages/bread/breadindex.js
var app = getApp();
var car = require('../../template/car/breadcar.js');
var category = require('../../template/category/breadcategory.js');
// var breadamt = require('../../template/breadamt/breadamt.js');

var allBread;
var pageScrollTop, pageScrollHeight;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topNeedShow: true,
    scrolltop: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var breadType = '1';
    this.setData({
      breadtype: breadType
    });
    car.init(this);
    // breadamt.init(this);
    if (app.globalData.address) {
      var address = app.globalData.address;
      this.setData({
        address: address
      });
    }
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var imghgt = res.windowWidth * 337 / 600;
        that.setData({
          imghgt: imghgt,
          scrollhgt: res.windowHeight
        });
      },
    });
    this.loadBreadList(this.data.breadType);
    pageScrollTop = 0;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.selectAddress.status == 1) {
      var address = app.globalData.selectAddress.value;
      this.setData({
        address: address
      });
      app.globalData.selectAddress.status = -1;
      app.globalData.selectAddress.value = null;

      this.loadBreadList(this.data.breadType);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  changeBreadType: function (e) {
    var btype = e.currentTarget.dataset.btype;
    if (btype == this.data.breadtype) {
      return;
    }
    this.setData({
      breadtype: btype
    });
    this.loadBreadList(btype);
    car.reset();
  },
  loadBreadList: function (btype) {
    app.appShowLoading(60000);
    var that = this;
    var curdate = app.currentDate();
    var pdtype = app.globalData.productType;
    if (pdtype == undefined) {
      app.getProductType();
      var timeid = setTimeout(function () {
        clearTimeout(timeid);
        that.loadBreadList(btype);
      }, 1000);
      return;
    }
    if (app.globalData.address == undefined || app.globalData.address == null) {
      app.getAddress();
      var timeid = setTimeout(function () {
        clearTimeout(timeid);
        that.loadBreadList(btype);
      }, 1000);
      return;
    }
    if (this.data.address == null || this.data.address == undefined) {
      var address = app.globalData.address;
      this.setData({
        address: address
      });
    }
    var city = this.data.address.CITYID;
    var url = '/yuanmai_we/product/productAll/' + city + '/' + pdtype + '/' + curdate;
    var property = {
      location: this.data.address.LOCATION,
      hasAddress: true,
      sortType: "default",
      ORDERSTARTDAY: "TODAY",
      MENUTYPE: "NORMAL"
    };
    var params = {
      __zaofans: true
    }
    if (btype == '1') {
      property.deliveryType = "normal";
    }
    else {
      property.deliveryType = "fast";
    }
    params.datas = JSON.stringify(property);
    app.loadDataFromServer(url, this.breadListCallBack, params, 'post');
  },
  breadListCallBack: function (res) {
    wx.hideToast();
    if (res.products == null || res.products == undefined) {
      this.setData({
        breadlist: []
      });
      wx.showModal({
        title: '',
        content: '当前地区没有商品可销售，是否返回首页？',
        confirmColor: '#a08257',
        confirmText: '是',
        cancelText: '否',
        success: function (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '../index/index',
            });
          }
        }
      });
      return;
    }
    var products = res.products;
    var breadlist = [];
    for (var i = 0; i < products.length; i++) {
      var breadinfo = {};
      breadinfo.goodsid = products[i].ID;
      breadinfo.name = products[i].NAME;
      if (products[i].fname != null && products[i].fname != undefined) {
        breadinfo.specs = products[i].fname.split(',');
      }
      else {
        breadinfo.specs = [];
      }
      if (products[i].fid != null && products[i].fid != undefined) {
        breadinfo.fid = products[i].fid;
      }
      else {
        breadinfo.fid = '';
      }
      breadinfo.img = products[i].PICTURE;
      breadinfo.price = products[i].PRICE;
      breadinfo.intro = products[i].SELLINGPOINT;
      breadinfo.mealid = products[i].MEALID;
      breadinfo.storeid = products[i].stationId;
      breadinfo.count = car.checkGoodsCount(breadinfo.mealid);
      breadlist.push(breadinfo);
    }
    this.setData({
      breadlist: breadlist,
      scrolltop: 0
    });
    allBread = breadlist;
    // -------- 初始化-------分类
    var cgritems = res.flavorList;
    cgritems.unshift({ name: '全部', id: '0' });
    category.init(this, cgritems, this.categoryChooseCallBack);
  },
  handleCount: function (e) {
    var options = parseInt(e.currentTarget.dataset.options);
    // if (options > 0) {
    //   var left = e.currentTarget.offsetLeft;
    //   var top = e.currentTarget.offsetTop - pageScrollTop;
    //   var url = '../imgs/car.png';
    //   breadamt.add(url, top, left);
    // }
    var goodsid = e.currentTarget.dataset.goodsid;
    var breadlist = this.data.breadlist;
    for (var i = 0; i < breadlist.length; i++) {
      if (breadlist[i].goodsid == goodsid) {
        var count = parseInt(breadlist[i].count);
        count += options * 1;
        count = count < 0 ? 0 : count;
        count = count > 9999 ? 9999 : count;
        breadlist[i].count = count;
        break;
      }
    }
    this.setData({ breadlist: breadlist });
    car.handleCount(e);
    // console.log(e.currentTarget);
  },
  addressHandle: function () {
    wx.showModal({
      title: '',
      content: '切换地址可能导致购物车中部分商品无效，是否继续？',
      confirmColor: '#a08257',
      confirmText: '是',
      cancelText: '否',
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '../my/address/address?type=select',
          });
        }
      }
    });
  },
  //-------------------CALL BACK FUC------------------
  categoryChooseCallBack: function (category_code) {
    console.log(category_code);
    if (category_code.id == '0') {
      this.setData({
        breadlist: allBread
      });
    }
    else {
      var breadlist = [];
      for (var i = 0; i < allBread.length; i++) {
        var fidArr = allBread[i].fid.split(',');
        if (fidArr.indexOf(category_code.id) >= 0) {
          breadlist.push(allBread[i]);
        }
      }
      for (var i = 0; i < allBread.length; i++) {
        if (breadlist.indexOf(allBread[i]) < 0) {
          breadlist.push(allBread[i]);
        }
      }
      this.setData({
        scrolltop: 0,
        breadlist: breadlist
      });
    }
    category.close();
  },
  goodsScroll: function (e) {
    // console.log(e.detail.scrollTop, e.detail.scrollHeight);
    pageScrollTop = e.detail.scrollTop;
    pageScrollHeight = e.detail.scrollHeight;
    var topNeedShow = true;
    if (e.detail.deltaY < 0 && e.detail.scrollTop > 90) {
      topNeedShow = false;
    }
    if (this.data.cgr_show == true) {
      topNeedShow = true;
    }
    // this.setData({
    //   topNeedShow: topNeedShow
    // });
  },
  //-----------------------------------
  showCar: car.showCar,
  submitOrder: car.submitOrder,
  closeCar: car.closeCar,

  showCategory: category.show,
  closeCategory: category.close,
  chooseCategory: category.choose,
  //-----------------------------------------
  toPageTop: function () {
    this.setData({
      scrolltop: 0
    });
  }
})